Skip to content

fix(daemon): settle an expired session lifetime once - #5000

Merged
thymikee merged 14 commits into
0.22from
t3/settle-expired-lifetime-4968
Nov 23, 2026
Merged

thymikee merged 14 commits into
0.22from
t3/settle-expired-lifetime-4968

Conversation

@thymikee

@thymikee thymikee commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Owner requests, sweeps, and successor opens share one expiry job per session lifetime. Closing addresses, run bindings, and devices stay reserved through cleanup and provider disposal. Provider-ended heartbeats hand off the exact issuance. Exact end proof settles the bound recording under its resource fence. Independent local cleanup still gates release while the daemon is live. Shutdown disposes expired rentals after failed local cleanup and reports the lease and failed steps. Expiry clears runtime hints on their bound app once. This removes inline teardown and early successor renewal.

Before / after

  • An expired owner close racing the sweep could tear down twice. The owner can now receive one confirmed endedLeases receipt with LEASE_NOT_FOUND.
  • A successor whose lease lapses during cleanup now receives LEASE_NOT_FOUND before launch.
  • 0.22 freed the device when provider release was refused. A non-durable refusal now fences allocation with DEVICE_LEASE_BUSY and releaseStatus: "unknown". ADR 0040 step 5 — Fence unresolved provider allocations #4969 tracks durable fencing and recovery.

Validation

Head 3e03199c6b uses 58c76a620f. Install, build, typecheck, lint, format, layering, Fallow, and wire checks passed. All 355 targeted and 11 fuzz-worker tests passed. Integration passed 155 Node and 319 provider tests with 13 opt-in live skips. Full Coverage passed 23,233 tests and failed three CLI help size assertions that also fail on 58c76a620f. check:affected stopped on the same three assertions. Raw session-store reads fell from 189 to 187.

Closes #4968

@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 5.04 MB 5.04 MB +8.3 kB
Package (unpacked) 5.04 MB 5.04 MB +8.3 kB
Package (download) 1.54 MB 1.54 MB +3.3 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 26.4 ms 30.5 ms +4.1 ms
CLI --help 56.1 ms 57.0 ms +0.9 ms

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on 3df17be. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

At 3df17be the settlement design is sound, but seven defects can still strand a session address, release a device too early, or skip a receipt. CI is still running, and no failure has been seen so far.

A second independent pass found that a fresh open can replace a lifetime while its provider release is pending. After cleanup retires the session (lease-lifecycle.ts:66), keep the provider release call pending or failing. An open of the same address with an already valid lease for a different device gets no SessionRef or settlement (request-execution-scope.ts:386). Lines 416 and 511-527 treat it as a fresh open, and session-store.ts:124-137 lets it publish. A shared-mode unleased open can publish in the same gap. The rule: while a lifetime is closing, it must stay discoverable by address under the session lock through both confirmations, and fresh requests must check it before an address counts as free.

A second independent pass found that provider release can start after failed cleanup (provider-lease-expiry.ts:313). If the first native finalization or resource stop fails, the session stays pending, but lease-session-end.ts:207 drops the boolean outcome. The releaser then treats the fulfilled promise as permission to release (lines 309-315) and forgets the dependency (lines 401-406). After release, the session retry runs against a device the provider already forgot. Limrun, for example, only resolves live leases (runtime.ts:805-831). A shutdown that cancels a queued expiry cleanup opens the same gate. The rule: provider release waits for confirmed session cleanup, the dependency survives cleanup retries, and shutdown or an exact provider-ended result resolves it through the same lease end record.

A second independent pass found that a lease without a device key loses its run reservation at expiry (lease-registry.ts:771). While the first lease is active, a second allocation with the same tenant, run and backend is busy (lines 220-237). After expiry the run binding is deleted (lines 663-667 and 731-737), and the ending-scope check at 759-771 returns early without a device key. A second lease is then issued and lease.ts:123-142 allocates from the provider while release of the first is pending. The rule: the run scope stays reserved until settlement completes, and a matching allocation gets the same typed contention refusal.

A second independent pass found that an owner close can skip settlement when expiry is detected during final admission (request-execution-scope.ts:513). Hold an owner close after resolveExpiryAdmission reads the lease as active (line 418), and let the deadline pass before admission at line 684. Admission sweeps the lease and starts its daemon job (request-admission.ts:237-245). The resulting LEASE_NOT_FOUND escapes from runLockPlan, so the owner returns before cleanup finishes and gets no receipt. The rule: locked admission that finds the addressed lease expired must return the existing need-settlement result, through the outside-lock wait and receipt path, or through step failure when outer locks are held.

A second independent pass found that a PID-pinned macOS successor can dispatch after its lease issuance expires (request-execution-scope.ts:687). The successor passes the pinned check and renews at lines 441-450 and 684. If the second PID lookup is slow, the sweep retires the lease because no work pass exists yet. The ID can be reissued through host PUT for another app or owner. The work pass and mutation guard (request-lease-work.ts:25-31) check the new issuance, while the request dispatches with its old admitted lease. The base held the pass through that lookup. The rule: the admitted-work pass must be installed with no await between the final pinned-issuance check and admission, or dispatch must be guarded against a replaced issuance.

A second independent pass found that a delayed provider-ended heartbeat can start a second cleanup owner (lease.ts:384). Hold a heartbeat reply past the renewed deadline, let the sweep start cleanup, then return PROVIDER_INSTANCE_ENDED. endProviderLease finds no live lease (lease-registry.ts:295-301), yet the handler starts a second end. The guard at lease-session-end.ts:177-180 covers only LEASE_EXPIRED. If the first cleanup records pending and the second then succeeds, it deletes the shared pending entry (lines 159-166) and neither sets sessionsSettled. The device stays reserved after cleanup and release are both confirmed. The rule: the expired lease end record owns this callback, and a provider-ended heartbeat starts cleanup only if it won the active-to-ending transition for its own issuance.

A second independent pass found that a provider-confirmed end can strand a live address after the rental is gone (lease-lifecycle.ts:61). A Limrun heartbeat reports the instance ended and its provider entry can vanish before teardown reaches a platform binding. If teardown then fails, the shared end path keeps the session and retries an operation that needs the missing device. PROVIDER_INSTANCE_ENDED publishes no settlement for that lifetime (lease-session-end.ts:177-223), so a valid open of the same address gets LEASE_NOT_FOUND indefinitely (request-execution-scope.ts:419-426). The base retired the address even when teardown threw. The rule: an exact provider-ended result settles cleanup that cannot survive that instance, while independent local cleanup keeps its own confirmation, and this route stays distinct from an unconfirmed TTL expiry.

A second independent pass found that the lease contract in remote-device-lease-contracts.md:104 is now wrong. Lines 102-105 say the successor starts admitted work before teardown. A successor whose lease expires during the old cleanup now gets LEASE_NOT_FOUND before launch (request-execution-scope.ts:452-468). Line 65 still guarantees a receipt when close finds an inactive lease, but the code emits one only after confirmed settlement within budget. Please update both passages to match.

Not blocking, and each can be taken or left: (1) ExpirySettlement.done resolves false after the first failed teardown or the first release attempt, so a successor gets DEVICE_IN_USE at once even with wait budget left, and the owner close gets no receipt although the end is confirmed later (lease-session-end.ts:210); (2) when an expiry joins an in-flight end for the same lease ID, end() returns early and never confirms sessionsSettled, for example after a host DELETE and re-PUT of the ID (lease-session-end.ts:178); (3) a reserved ending lease refuses allocation with 'Device is already leased', a past expiresAt and a 'retry after the lease expires' hint, which misleads the caller (lease-registry.ts:770); (4) enforceCapacity ignores ending entries, so an expiring ios-simulator lease frees capacity while teardown runs, unless ADR 0007 states that the reservation fences the device binding only; (5) the new --wait usage line implies open waits for a busy device by default, but without --wait it still fails at once, so 'Open: wait up to n ms for a busy device; also caps the wait for expired-session cleanup' would be accurate (flag-definitions-workflow.ts:99).

Could the registry's lease end record own completion instead? reserveExpiredLease(lease) would return or keep a record with a settled promise that confirmExpiredLeaseEnd resolves once sessionsSettled and providerReleased are both true. LeaseSessionEnd would confirm only sessionsSettled, and settlementFor(lifetime) would map lifetime to lease ID to registry record. That deletes the finishProvider deferred in daemon-runtime.ts:282-311, the providerEnd parameter of end(), and the confirmExpiredSessions callback. It also lets a successor wait through retries within its budget and gives one place to fence capacity. ADR 0007 already names a single lease end record, so nothing has to change first.

Smoke Tests on ios, macos and android, Lint/Typecheck/Package and Coverage were still in progress, and no failure was seen. The diff rewrites the locked admission and lock-planning loop that every open, command and close passes through, so a smoke failure would likely be related. Green Smoke Tests on ios, macos and android at this commit are required before merge, since they exercise open, command and close through that loop. The lease-expiry route itself is daemon-only and covered by the HTTP settlement tests with a fake runtime, so it needs no extra device run.

Not verified here: any test run, including whether the new HTTP settlement tests fail on the base, the base double-teardown from #4949, the session-store read counts in the PR body, the torture seeds and the layering results. Also not verified here: whether hosts re-PUT a lease ID inside a teardown window in practice.

The next step is to fix the seven defects and let all checks finish green.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on 08dd3bc. The verdict and the full list are in the summary comment.

@apex-sentinel-staging

This comment has been minimized.

@thymikee
thymikee force-pushed the t3/settle-expired-lifetime-4968 branch from d89dead to 4c559e8 Compare November 23, 2026 10:11
@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on 4c559e8. The verdict and the full list are in the summary comment.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on 9f876c4. The verdict and the full list are in the summary comment.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Two high-priority problems from the earlier review remain at f9d5fa5. The rest of those findings are fixed: a refused expiry reports an unknown release, a registry-held lease is no longer reserved for expiry, leased_session_ended covers all three reasons, and a failed teardown under PROVIDER_INSTANCE_ENDED now retires the session.

When a Limrun instance ends externally, its heartbeat throws PROVIDER_INSTANCE_ENDED and wins endProviderLease (lease.ts:397). The registry deletes the lease, calls onLeaseExpired, and then updates the live journal (lease-registry.ts:298-306). The callback returns early at daemon-runtime.ts:299, so expiredProviderLeaseReleaser.release never runs. The heartbeat does not dispose the owner; only release() does (runtime.ts:782-811). The keep-alive timer, Android ADB endpoint, iOS runner transport and capture HAR record leak for the daemon's lifetime, and a crash leaves no recovery record. The base passed every reason to the releaser, and ADR 0007 says the lease end record covers provider release. A second independent pass found the same gap from the journal side: the journal drops the lease before disposal starts, and the session address can be reused meanwhile. The rule: every route that removes a provider lease from the registry hands that exact lease to the releaser once, before the live journal update, and holds its reservation through session settlement and disposal. Please remove the early return for PROVIDER_INSTANCE_ENDED, and add a daemon-runtime test where a provider-ended heartbeat calls release or recovery once.

A second independent pass found another provider-ended case. Start a Limrun recording and hold the heartbeat reply past the renewed TTL. The sweep takes the lease and recording stop fails against the ended instance (recording-runtime.ts:81-89). When the heartbeat then returns PROVIDER_INSTANCE_ENDED, isCurrent() is false, so the handler only returns the error. The existing job retries with LEASE_EXPIRED, and the provider-ended handling at lease-session-end.ts:114-136 never applies. The closing address stays fenced and disposal stays behind the cleanup gate. The rule: a late provider-ended result for the heartbeat's captured issuance confirms instance termination on the existing end record, and that job settles instance-bound cleanup from it. Independent local cleanup keeps its own confirmation.

Shutdown can also leave the expiry release gate closed. If shutdown starts while an expired provider lease's teardown is in flight or waiting on an execution lock, closeSteps calls leaseSessionEnd.cancel() (daemon-runtime.ts:776). The in-flight cleanup then computes retired = !closing && … as false (lease-session-end.ts:302). A pending retry returns at line 290, so provider.allowRelease() never runs. The shutdown teardown later cleans the session but only reports counts (daemon-runtime.ts:424-431). A lease first consumed by listActiveLeases during finalization hits the same gate (daemon-lease-finalizer.ts:38-47). The release attempt then waits forever on after (provider-lease-expiry.ts:309-317), and the drain times out without calling the provider. A live, non-recoverable lease stays rented until the provider's own timeout. The base sent the release at expiry. The rule: the release gate opens once all cleanup for that lease is confirmed, whoever confirms it. Please compute retired from the pending state alone and use closing only to stop new retries. Please have shutdown session teardown and retained-host cleanup feed their successful outcomes into the same expiry record, including leases first consumed during shutdown, before expiredProviderLeaseReleaser.drain. Add a test where shutdown starts mid-teardown and the provider hook is still called.

Not blocking: settleExpiredSession's providerEnded branch (session-teardown.ts:230) tolerates only a typed instance-ended error, while teardownForLeaseEnd already catches every failure under PROVIDER_INSTANCE_ENDED. The two guards differ only in diagnostic level. Dropping the flag, the reason parameter threaded into settleIdleExpiredSession, and the test 'device finalization after provider end settles only on exact proof' would leave one catch. These can be taken or left.

Of the open inline threads, the one on the shutdown release gate still applies if it is open; the lower-priority threads that still apply number zero. These do not apply and can be resolved: the lifetime fence after a non-durable refusal is intended under ADR 0040, and durable fencing is #4969 (thread). The expiry reservation now refuses when the registry holds the lease ID, and consume unbinds before the callback (thread). leased_session_ended is emitted for all three reasons and names each session (thread). Teardown failures under PROVIDER_INSTANCE_ENDED now retire the session, with a test (thread).

All 15 checks at f9d5fa5 are queued or in progress, and the one non-passing run is a cancelled Body rules run that a newer run replaced. The delta changes the locked admission attempt in request-execution-scope.ts:484-540, which every open, command and close uses, so green Smoke Tests (ios, macos, android) and Integration Tests at this commit are required before merge. The lease-expiry route itself is daemon-only and its tests cover it, so it needs no extra device run. No conflicts are known.

Not verified here: tests were not run locally, the new provider-end retire, run-binding and need-settlement tests were not confirmed to fail on c461f66, and whether Limrun disposes leftover owners on daemon close. If it does, the first leak is bounded to the process lifetime, but the missing release still holds. The shutdown case is traced from code and not reproduced, and its impact depends on recoverableProviderIds: a recoverable provider is bounded by its pending record until the next daemon start. The review covers the logical patch c461f66..f9d5fa5, not the 0.22 rebase.

Before merge, restore the provider release for PROVIDER_INSTANCE_ENDED at daemon-runtime.ts:299, open the expiry release gate when shutdown confirms cleanup at lease-session-end.ts:302, and let Smoke Tests and Integration Tests finish green.

@thymikee

Copy link
Copy Markdown
Member Author

I traced the review findings on f9d5fa5. The shutdown fix needs to address both guards. run leaves the pending entry in place while closing is set, so checking that entry alone still leaves the provider release waiting. Shutdown needs to confirm cleanup of the owned sessions and retained hosts on the existing lease-end record before the release drain. The late heartbeat also needs to identify the same issuance on that record after the active lease is removed. Coverage, Integration Tests, and the Apple and Android smoke checks are green in the PR view. Linux smoke setup stopped at the apt-get update timeout.

@thymikee
thymikee force-pushed the t3/settle-expired-lifetime-4968 branch from f9d5fa5 to 7c93601 Compare November 23, 2026 11:36
@thymikee

Copy link
Copy Markdown
Member Author

Fixed in 7c93601ae702929a9b369340f06a06beccf249ac for the three merge blockers.

  1. Provider-ended heartbeat hands the captured lease to the releaser before the registry updates the live journal and keeps the reservation through session cleanup and disposal.
  2. Late heartbeat proof applies to the captured issuance on the existing end record. It settles the provider recording while independent local cleanup still gates release.
  3. Shutdown feeds successful session and retained-host cleanup into that record, including a lease first consumed by the finalizer, before draining provider releases.

All three daemon-runtime tests failed on f9d5fa5 and passed on the rebased head. Targeted tests, full Coverage, and local integration passed.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 2 new findings on 7c93601. The verdict and the full list are in the summary comment.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

The three problems from the earlier review are fixed at 78b99a2, but a second independent pass found two defects that still need a change.

A second independent pass found that a provider-ended heartbeat can confirm a failed local cleanup. When a heartbeat wins removal of an active lease with an open session and a local teardown step fails (for example removing a retained materialized path), the provider-ended branch logs the failure and returns successfully. The claim is then cleared and the session retired, the pending entry is removed and sessionsSettled is recorded, and the provider gate and the device and run reservation are released. A successor can reuse the scope while local cleanup is unproven, and an owner close that is already waiting can get a confirmed endedLeases receipt. Please rethrow the teardown error after the provider-ended diagnostic is emitted, so the existing settlement keeps the claim and scope fenced and can retry. The heartbeat caller should still get the original typed provider-ended error.

A second independent pass also found that recording teardown still calls the provider after exact end proof exists. For a Limrun screen recording, when a provider-ended heartbeat wins the lease, or a late heartbeat pins proof before the next cleanup attempt, finishSessionScreenRecording enters finishLiveScreenRecording before it reads the proof. That calls stopRecording on the ended instance, and a failed stop can trigger a second call through disposal. A hanging stop keeps confirmLiveMissing from running, so local cleanup and provider disposal wait despite the end proof. The rule is that no native recording call starts once the exact issuance has proof of end for the bound recording. Please check that proof and the recording's ownership before provider disposal, confirm the descriptor as missing under its existing resource fence, and continue the other cleanup steps. Please also recheck at the provider call boundary, because proof can arrive during a fence wait or a failed finish.

Not blocking: the same swallow-all behavior under provider-ended also skips host-local steps and resource failures in settleExpiredSession, so the maintainer may want a follow-up issue to classify teardown steps by owner, and the same recording path could check providerInstanceEnded() before finishLiveScreenRecording, so these can be taken or left.

Of the earlier inline threads, no high-priority thread and no lower-priority thread still applies. The shutdown allowRelease() thread is fixed at this head, and the lease-lifecycle.ts:65 thread matches ADR 0040, with retry and fencing policy deferred to #4969, so both can be resolved.

The only check that has not passed is Body rules, which was cancelled and looks like a superseded run, so it is likely unrelated. The other 16 checks pass at 78b99a2, including the smoke and integration jobs that run daemon shutdown. There are no known conflicts. Before merge, the two defects above need a fix, and the cancelled Body rules run needs a re-run. Not verified here: the tests were not run locally, and whether Limrun stopRecording on an ended instance is bounded by a client timeout. If it can hang, the recording defect would hold the expiry job with the scope fenced rather than only add latency.

@thymikee
thymikee force-pushed the t3/settle-expired-lifetime-4968 branch from 879af35 to 3e03199 Compare November 23, 2026 13:54
@thymikee

Copy link
Copy Markdown
Member Author

The code in 3e03199 looks good, and the two high-priority findings from the earlier review (#5000 (comment)) are fixed. No code change is needed. The shutdown release concern still holds: finishShutdown allows release for every pending lease, and onLeaseExpired gates the releaser on session end. The thread at #5000 (comment) is fixed at this head and can be resolved. The thread at #5000 (comment) is about retry policy when clearDeviceClaim returns 'unattributable'. It is deferred to #4969 and this change does not touch it, so it can be resolved too.

CI is still running at this head. Checks in progress include Integration Tests and Coverage, and the three smoke jobs. Body rules was cancelled, most likely by a superseded run, so it needs a re-run. Tests were not run locally. Not verified here: whether provider-side teardown steps fail every time against an ended Limrun instance. If they do, the rethrow keeps the claim and reservation fenced until shutdown releases them, which matches the stated rule. Not verified here: whether Limrun stopRecording has a client timeout. This only matters for a finish that started before proof arrived. Once Integration Tests and Coverage pass and Body rules is re-run, this is ready to merge.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 23, 2026
@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of 3e03199

Since the review of 78b99a2: 0 new · 0 still open · 0 no longer raised

No open findings.

1 finding below minor hidden (user_settings.min_severity).

Reviewed with this repository's own Sentinel configuration (aecafaf30537).

💬 Talking to Sentinel

In a finding's thread, reply with:

Command What it does
@apex-sentinel-staging note <context> Adds context; Sentinel re-checks the cited code
@apex-sentinel-staging pivot <why> Says the finding is wrong; Sentinel re-checks the cited code
@apex-sentinel-staging like Marks the finding as useful
@apex-sentinel-staging dislike <why> Marks it as not useful, so it is not raised again

On this conversation, comment @apex-sentinel-staging review to run a full review once again.

@thymikee
thymikee merged commit a64cfa9 into 0.22 Nov 23, 2026
19 of 22 checks passed
@thymikee
thymikee deleted the t3/settle-expired-lifetime-4968 branch November 23, 2026 14:17
thymikee added a commit that referenced this pull request Nov 24, 2026
* fix(daemon): settle an expired session lifetime once

* fix(daemon): defer expiry helpers until startup or use

* fix: align open wait docs and lease admission tests

* fix(daemon): report unknown provider release on reserved devices

* fix(daemon): preserve lease fences across settlement retries

* fix(daemon): load provider end proof only when needed

* fix(daemon): reject stale expiry reservations for live leases

* fix(daemon): reconcile expiry settlement with rebased 0.22

* fix(daemon): restore per-session lease end diagnostics

* fix(daemon): retire sessions after confirmed provider end

* fix(daemon): finish provider leases across heartbeat and shutdown

* fix(daemon): release expired rentals after shutdown teardown

* fix(daemon): preserve local cleanup fences after provider end

* fix(daemon): record confirmed runtime hint cleanup before retry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Valid work that needs human implementation, judgment, or maintainer merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant